package com.fighYo.trace.controller;


import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fighYo.trace.entity.Info;
import com.fighYo.trace.entity.Payment;
import com.fighYo.trace.entity.Product;
import com.fighYo.trace.entity.User;
import com.fighYo.trace.entity.query.PaymentQuery;
import com.fighYo.trace.entity.query.ProductQuery;
import com.fighYo.trace.entity.vo.ProductVo;
import com.fighYo.trace.service.*;
import com.fighYo.trace.utils.R;
import com.fighYo.trace.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fighYo
 * @since 2022-04-13
 */
@Slf4j
@CrossOrigin
@Api(tags = {"订单管理"})
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private UserService userService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private InfoService infoService;

    @Autowired
    private ProductService productService;

    @Autowired
    private QrcodeService qrcodeService;

    @ApiOperation("总数")
    @GetMapping("count")
    public R count() {
        int count = paymentService.count(null);
        return R.ok().data("item", count);
    }

    @ApiOperation("根据订单ID获取订单信息")
    @GetMapping("get")
    public R getPayment(Integer paymentId) {
        Payment payment = paymentService.getById(paymentId);
        return R.ok().data("item", payment);
    }

    @ApiOperation("添加订单")
    @PostMapping("add")
    public R addPayment(@RequestBody Payment payment) {

        Product product = productService.getById(payment.getProductId());

        if (product.getQuantity().intValue() < payment.getQuantity().intValue()) {
            return R.error().msg("库存不足");
        }

        payment.setSellerId(product.getUserId());

        Info sellerInfo = infoService.getUserInfo(payment.getSellerId());
        Info buyerInfo = infoService.getUserInfo(payment.getBuyerId());
        User buyer = userService.getById(payment.getBuyerId());

        if (buyerInfo == null || buyerInfo.getName() == null || buyerInfo.getTel() == null) {
            return R.error().msg("个人信息未完善");
        }

        product.setQuantity(product.getQuantity() - payment.getQuantity());
        payment.setBuyerType(buyer.getUserType());
        payment.setSellerRealName(sellerInfo.getName());
        payment.setSellerTel(sellerInfo.getTel());
        payment.setBuyerTel(buyerInfo.getTel());
        payment.setJudgeFlag("0");

        productService.updateById(product);

        payment.setBuyerRealName(buyerInfo.getName());
        payment.setImg(product.getImg());

        payment.setHappenTime(new Date());
        boolean result = paymentService.save(payment);

        productService.addQuantity(payment);

        return result ? R.ok() : R.error().msg("购买失败");
    }

    private String getTotalCost(List<Payment> list) {

        if (list == null || list.size() == 0) {
            return "0";
        }

        BigDecimal total = new BigDecimal("0");

        for (Payment payment : list) {
            BigDecimal value = new BigDecimal(payment.getAmount());
            total = total.add(value);
        }
        return total.toString();
    }

    @ApiOperation("根据当前用户获取订单列表")
    @PostMapping("listByUser")
    public R getPaymentByUser(HttpServletRequest request) {
        String userId = request.getHeader("access-token");

        QueryWrapper sellWrapper = new QueryWrapper();
        sellWrapper.eq("seller_id", userId);
        sellWrapper.orderByDesc("happen_time");
        List sellList = paymentService.list(sellWrapper);

        QueryWrapper buyWrapper = new QueryWrapper();
        buyWrapper.eq("buyer_id", userId);
        buyWrapper.orderByDesc("happen_time");
        List buyList = paymentService.list(buyWrapper);

        List<Payment> paymentList = new ArrayList<>();

        paymentList.addAll(sellList);
        paymentList.addAll(buyList);

        return R.ok().data("sellList", sellList).data("buyList", buyList).data("income", getTotalCost(sellList)).data("cost", getTotalCost(buyList));
    }

    @ApiOperation("审批溯源码")
    @PostMapping("judge")
    public R judgePayment(@RequestBody Payment payment) {

        String judgeFlag = payment.getJudgeFlag();
        payment = paymentService.getById(payment.getId());

        if (payment.getJudgeFlag().equals("1")) {
            return R.error().msg("该订单已生成溯源码");
        }

        payment.setJudgeFlag(judgeFlag);

        if (judgeFlag.equals("1")) {
            try {
                Integer quantity = payment.getQuantity();
                if (payment.getJudgeFlag().equals("1")) {
                    for (int i = 0; i < quantity; i++) {
                        qrcodeService.createQR(payment);
                    }
                }
            } catch (Exception ex) {
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("payment_id", payment.getId());
                qrcodeService.remove(wrapper);
                return R.error().msg("生成溯源码失败");
            }
        }

        paymentService.updateById(payment);
        return R.ok();
    }

    @ApiOperation("分页获取订单信息")
    @PostMapping("page/{cur}/{limit}")
    public R pageTeacherCondition(@PathVariable("cur") long cur,
                                  @PathVariable("limit") long limit,
                                  @RequestBody PaymentQuery paymentQuery) {
        Page<Payment> page = new Page<>(cur, limit);

        QueryWrapper<Payment> wrapper = new QueryWrapper<>();

        String userName = paymentQuery.getUserName();
        String productName = paymentQuery.getProductName();
        String buyerType = paymentQuery.getBuyerType();
        Date startTime = paymentQuery.getStartTime();
        Date endTime = paymentQuery.getEndTime();
        String judgeFlag = paymentQuery.getJudgeFlag();


        if(!StringUtils.isEmpty(userName)) {
            wrapper.and(tmpWrapper -> tmpWrapper.like("seller_real_name", userName).or().like("buyer_real_name", userName));
        }

        if(!StringUtils.isEmpty(productName)) {
            wrapper.like("product_name", productName);
        }

        if(!StringUtils.isEmpty(buyerType)) {
            wrapper.eq("buyer_type", buyerType);
        }

        if(startTime != null) {
            wrapper.ge("happen_time", TimeUtil.dateFormat(startTime));
        }

        if(endTime != null) {
            wrapper.le("happen_time", TimeUtil.dateFormat(endTime));
        }

        if(!StringUtils.isEmpty(judgeFlag)) {
            wrapper.like("judge_flag", judgeFlag);
        }

        paymentService.page(page, wrapper);

        long total = page.getTotal();
        List<Payment> records = page.getRecords();
        return R.ok().data("total", total).data("list", records);
    }

    @ApiOperation("获取产品详细信息")
    @GetMapping("/detail")
    public R detail(String id) {
        Payment payment = paymentService.getById(id);
        return R.ok().data("item", payment);
    }
    
}

